<template>
  <div class="dic-manage">
    <div>
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline">
        <el-form-item prop="dictName">
          <el-input v-model="formInline.dictName" placeholder="字典名称"></el-input>
        </el-form-item>
        <el-form-item prop="dictCode">
          <el-input v-model="formInline.dictCode" placeholder="字典编码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="check-box" type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="resetForm('formInline')">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button @click="newCode()" class="new-button">新建编码</el-button>
    </div>
    <!-- main表格-->
    <el-table :data="tableData" border class="main-table" :header-cell-style="{
      background: '#f0f7fe',
      color: '#467ee1',
      fontSize: '16px',
    }" row-key="id" lazy :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="100">
        <template slot-scope="{ $index }">
          {{ startIndex + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="dictName" label="字典名称" align="center">
      </el-table-column>
      <el-table-column prop="dictCode" label="字典编码" width="180" align="center">
      </el-table-column>
      <el-table-column prop="pid" label="父级字典" align="center">
        <template slot-scope="scope">
          {{ getDictName(scope.row.pid) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="0" inactive-value="1" disabled>
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.remark ? scope.row.remark : "无" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
      </el-table-column>
      <el-table-column prop="action" label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="inducts(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="HandleDeletes(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-change="currentPage"
        :page-sizes="[10, 20, 30, 40]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 弹出框 -->
    <el-dialog title="新增/修改字典" :visible.sync="dialogVisible" width="30%" @close="dialogcancle()">
      <el-form ref="ruleForm" :rules="dialogrules" :model="form" class="form-item">
        <el-form-item prop="dictName" label="字典名称" :label-width="formLabelWidth">
          <el-input v-model="form.dictName"></el-input>
        </el-form-item>
        <el-form-item prop="dictCode" label="字典编码" :label-width="formLabelWidth">
          <el-input v-model="form.dictCode"></el-input>
        </el-form-item>
        <el-form-item prop="pid" label="上级字典" :label-width="formLabelWidth">
          <el-select v-model="form.pid" placeholder="请选择上级字典" :disabled="disabled">
            <el-option v-for="(item, index) in dictPid" :label="item.dictCode" :value="item.id" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="状态" :label-width="formLabelWidth">
          <el-switch v-model="form.status" :active-value="0" inactive-value="1"></el-switch>
        </el-form-item>
        <el-form-item prop="remark" label="备注" :label-width="formLabelWidth">
          <el-input type="textarea" :rows="5" placeholder="请输入" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogcancle()">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script scoped>
import {
  deleteDict,
  getDictPageTreeByCode,
  saveDict,
  updateDict,
  getDictSelect,
} from "../api/dict";

export default {
  data() {
    return {
      dialogrules: {
        dictName: [
          { required: true, message: "请输入编码名称", trigger: "blur" },
        ],
        dictCode: [
          { required: true, message: "选择字典编码", trigger: "blur" },
        ],
      },
      //分页属性
      displayedData: [], // 当前页显示的数据
      currentPage: 1, // 当前页面
      pagesize: 10, // 每页显示的数据条数
      total: 0, // 总数据条数
      startIndex: 0, //当前页数据的起始索引
      form: {}, //新建弹出框表单
      dictPid: [], //上级字典(父级)列表
      formLabelWidth: "100px", //弹出框表单的lable宽度
      dialogVisible: false, //弹出框的值
      formInline: {
        //搜索表单
        dictName: "",
        dictCode: "",
      },
      TableIndex: "", //编辑行索引
      TableRow: {}, //编辑行信息
      tableData: [], //main展示表单信息
      disabled: false,
    };
  },
  methods: {
    indexMethod(index) {
      return index + 1 + (this.pagination.currentPage - 1) * this.pagination.pagesize
    },
    //改变每页条数
    handleSizeChange(value) {
      this.pagesize = value;
    },
    //改变当前页触发
    handleCurrentChange(value) {
      this.currentPage = value;
      this.startIndex = (value - 1) * this.pagesize;
      this.displayedData = this.tableData
        .slice(this.startIndex, this.startIndex + this.pagesize)
        .map((row, index) => {
          return {
            ...row,
            index: this.startIndex + index + 1,
          };
        });
    },
    //删除整行数据
    HandleDeletes(index, row) {
      // console.log(index, 222, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteDict(row.id).then((res) => {
          this.getDictTree();
        });
      });
    },
    //搜索重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getDictTree();
    },
    // 点击编辑字典
    inducts(index, row) {
      this.TableIndex = index;
      this.form = row;
      this.newCode();
    },
    //打开弹出框
    newCode() {
      this.dialogVisible = true;
      this.getPDict();
    },
    // 获取上级字典（父级）
    getPDict() {
      getDictSelect({}).then((res) => {
        this.dictPid = res.data.data;
      });
      if (this.form.pid == "0") {
        this.form.pid = "无";
        this.disabled = true;
      } else {
        this.disabled = false;
      }
    },
    //字典保存或修改
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //校验通过走这里
          if (this.form.id) {
            // 修改字典
            updateDict({
              id: this.form.id,
              dictName: this.form.dictName,
              dictCode: this.form.dictCode,
              pid: this.form.pid === "无" ? "0" : this.form.pid,
              status: this.form.status,
              remark: this.form.remark,
            }).then((res) => {
              this.getDictTree();
            });
          } else {
            //保存新建字典
            saveDict({
              dictName: this.form.dictName,
              dictCode: this.form.dictCode,
              pid: this.form.pid === "无" ? "0" : this.form.pid,
              status: this.form.status,
              remark: this.form.remark,
            }).then((res) => {
              this.getDictTree();
            });
          }
          this.$message({
            showClose: true,
            message: "字典保存成功",
            type: "success",
          });
          this.dialogcancle();
        } else {
          return false;
        }
      });
    },
    //点击弹出框的退出图标清空弹出框表单内容或清空弹出框表单内容
    dialogcancle() {
      this.form = {};
      this.dialogVisible = false;
    },
    // 查询字典列表
    getDictTree() {
      getDictPageTreeByCode({
        dictName: this.formInline.dictName,
        dictCode: this.formInline.dictCode,
        pageNum: this.currentPage,
        pageSize: this.pagesize,
      }).then((res) => {
        this.tableData = res.data.data.treeList;
        this.total = res.data.data.total;
        // console.log(res.data.data.treeList);
        // console.log(this.total);
      });
    },
    // 查询信息
    onSubmit() {
      this.tableData = [];
      this.getDictTree();
    },
    // 根据父级Pid获取上级字典
    getDictName(pid) {
      const item = this.tableData.find((item) => item.id === pid);
      return item && item.dictCode ? item.dictCode : "无";
    },
  },
  watch: {
    currentPage: function (newvalue) {
      this.getDictTree(newvalue);
    },
    pagesize: function (newvalue) {
      this.getDictTree(newvalue);
    },
  },
  mounted() {
    this.getDictTree();
  },
};
</script>
<style scoped>
.dic-manage {
  padding-top: 20px;
}

.title {
  height: 50px;
  font-weight: bold;
  line-height: 50px;
  background-color: #f9f9f9;
  margin-bottom: 20px;
  padding-left: 10px;
  font-size: 20px;
  border: 1px solid #e9e9e9;
  border-radius: 5px;
  font-size: 17px;
  font-weight: bolder;
  padding: 0 20px;
  margin-bottom: 20px;
}

.form-item .el-form-item {
  width: 80%;
}

.el-form--inline .el-form-item {
  margin-right: 20px !important;
}

.check-box {
  margin-right: 10px;
}

.form-item .el-select {
  width: 100%;
}

.main-table {
  width: 100%;
  margin-top: 15px;
}

.tablecolumn {
  background-color: blue;
}

.new-button {
  margin-right: 10px;
}

.el-pagination {
  margin: 25px 0;
}

:deep(.el-pager li.active) {
  color: #ffffff;
  background-color: #409eff;
}

:deep(.el-pager li:hover) {
  color: #787d83;
}
</style>
